<?php
    $owner = $link->owner();

    $current_url = url('link', ['id' => $link->id]);

    if ($current_user) {
        $owner_is_current_user = $current_user->id === $owner->id;

        $suggested_links = $current_user->suggestedLinksFor($link);
        $owned_link = $current_user->correspondingOwnedLink($link);
        if ($owned_link && $link->user_id !== $current_user->id) {
            array_unshift($suggested_links, $owned_link);
        }

        $in_bookmarks = $link->isInBookmarksOf($current_user);
        $is_read = $link->isReadBy($current_user);
    } else {
        $owner_is_current_user = false;
        $owned_link = null;
        $suggested_links = [];
        $in_bookmarks = false;
        $is_read = false;
    }

    $open_graph = [
        'title' => _f('Shared on %s: %s', get_app_configuration('brand'), $link->title),
        'description' => _f('A link shared by %s on %s.', $owner->username, get_app_configuration('brand')),
        'locale' => $owner->locale,
        'url' => url_full('link', ['id' => $link->id]),
    ];
    if ($link->image_filename) {
        $open_graph['image'] = url_media_full('cards', $link->image_filename);
    }

    $this->layout('base.phtml', [
        'title' => $link->title,
        'canonical' => url_full('link', ['id' => $link->id]),
        'alternates' => [
            [
                'type' => 'application/atom+xml',
                'url' => url_full('link feed', ['id' => $link->id]),
                'title' => _f('Syndication feed of notes on %s', $link->title),
            ],
        ],
        'open_graph' => $open_graph,
        'has_errors' => $form && $form->isInvalid(),
    ]);
?>

<div class="section section--longbottom">
    <?php if ($link->image_filename): ?>
        <a
            target="_blank"
            rel="noopener noreferrer"
            href="<?= protect($link->url) ?>"
            tabindex="-1"
        >
            <img
                class="section__image"
                alt="<?= protect($link->title) ?>"
                src="<?= url_media('large', $link->image_filename) ?>"
            />
        </a>
    <?php endif; ?>

    <div class="section__title">
        <h1>
            <a
                class="anchor--hidden"
                target="_blank"
                rel="noopener noreferrer"
                href="<?= protect($link->url) ?>"
                tabindex="-1"
            >
                <?= protect($link->title) ?>
            </a>
        </h1>
    </div>

    <?php if ($link->tags): ?>
        <div class="link__tags link__tags--center">
            <?php foreach ($link->tags as $tag): ?>
                <a class="tag" href="<?= url('links', ['q' => "#{$tag}"]) ?>">
                    #<?= $tag ?>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <p class="section__intro">
        <?php if (!$link->fetched_at): ?>
            <span>
                <?= icon('sync', 'spin') ?>
                <?= _('ongoing synchronisation…') ?>
            </span>
        <?php else: ?>
            <?= protect($link->host()) ?>&nbsp;·&nbsp;<?= format_reading_time($link->reading_time) ?>
        <?php endif; ?>
    </p>

    <section class="wrapper wrapper--text wrapper--center flow">
        <div class="cols cols--always cols--center cols--gap">
            <p class="col--extend">
                <?php $username = $owner_is_current_user ? _('you') : protect($owner->username); ?>
                <?= _f('Added by <a href="%s">%s</a>', url('profile', ['id' => $owner->id]), $username) ?>
            </p>

            <div>
                <a
                    class="anchor--action"
                    target="_blank"
                    rel="noopener noreferrer"
                    href="<?= protect($link->url) ?>"
                >
                    <?= icon('pop-out') ?>
                    <?= _('read') ?>
                    <span class="sr-only">
                        <?= _('(open a new window)') ?>
                    </span>
                </a>
            </div>
        </div>

        <?php if ($current_user): ?>
            <div class="cols cols--always cols--gap-small">
                <div class="col--extend cols cols--always cols--gap-small">
                    <?php if (!$is_read || $in_bookmarks): ?>
                        <form data-turbo-preserve-scroll method="post" action="<?= url('mark link as read', ['id' => $link->id]) ?>">
                            <button class="button--icon" title="<?= _('Mark as read') ?>">
                                <?= icon('check') ?>
                                <span class="sr-only">
                                    <?= _('Mark as read') ?>
                                </span>
                            </button>

                            <input type="hidden" name="csrf_token" value="<?= csrf_token('links\\MarkLinkAsRead') ?>" />
                        </form>
                    <?php endif; ?>

                    <?php if (!$in_bookmarks): ?>
                        <form data-turbo-preserve-scroll method="post" action="<?= url('read link later', ['id' => $link->id]) ?>">
                            <button class="button--icon" title="<?= _('Read later') ?>">
                                <?= icon('bookmark') ?>
                                <span class="sr-only">
                                    <?= _('Read later') ?>
                                </span>
                            </button>

                            <input type="hidden" name="csrf_token" value="<?= csrf_token('links\\MarkLinkAsReadLater') ?>" />
                        </form>
                    <?php endif; ?>
                </div>

                <button
                    data-controller="modal-opener"
                    data-action="modal-opener#fetch"
                    data-modal-opener-href-value="<?= url('link collections', ['id' => $link->id]) ?>"
                    aria-haspopup="dialog"
                    aria-controls="modal"
                >
                    <?= icon('collection') ?>
                    <?= _('Store the link') ?>
                </button>
            </div>
        <?php endif; ?>
    </section>

    <section class="wrapper wrapper--text wrapper--center flow flow--larger" id="notepad">
        <hr>

        <div class="flow flow--large">
            <div class="flow">
                <h2 class="text--center text--normal">
                    <?= _('Notepad') ?>
                </h2>

                <?php if ($link->is_hidden): ?>
                    <p class="paragraph--centered paragraph--secondary">
                        <?= _('This link being hidden, the notes are private.') ?>
                    </p>
                <?php endif; ?>

                <?php $notepad = $link->notepad(); ?>
                <?php if ($notepad): ?>
                    <article class="notepad flow flow--large">
                        <?php foreach ($notepad as $date_iso => $notes): ?>
                            <?php $date = new \DateTimeImmutable($date_iso); ?>
                            <div id="notepad-<?= $date_iso ?>" class="flow">
                                <p>
                                    <a class="notepad__date" href="#notepad-<?= $date_iso ?>">
                                        <time datetime="<?= $date_iso ?>">
                                            <?= _d($date, 'dd MMMM y') ?>
                                        </time>
                                    </a>
                                </p>

                                <?php foreach ($notes as $note): ?>
                                    <div class="notepad__container cols cols--gap">
                                        <div class="notepad__note col--extend">
                                            <?= $note->contentAsHtml() ?>
                                        </div>

                                        <div class="text--right">
                                            <?php if ($current_user && $note->user_id === $current_user->id): ?>
                                                <details
                                                    class="popup"
                                                    data-controller="popup"
                                                    data-action="toggle->popup#update click@window->popup#closeOnClickOutside keydown->popup#closeOnEscape"
                                                >
                                                    <summary class="popup__opener" title="<?= _('Actions') ?>">
                                                        <span class="button button--ghost button--smaller">
                                                            <?= icon('menu') ?>
                                                            <span class="sr-only">
                                                                <?= _('Actions') ?>
                                                            </span>
                                                        </span>
                                                    </summary>

                                                    <nav class="popup__container popup__container--left" role="menu">
                                                        <button
                                                            class="popup__item popup__item--button"
                                                            data-controller="modal-opener"
                                                            data-action="modal-opener#fetch"
                                                            data-modal-opener-href-value="<?= url('edit note', ['id' => $note->id]) ?>"
                                                            aria-haspopup="dialog"
                                                            aria-controls="modal"
                                                            role="menuitem"
                                                        >
                                                            <?= icon('pencil') ?>
                                                            <?= _('Edit') ?>
                                                        </button>

                                                        <div class="popup__separator"></div>

                                                        <form
                                                            data-turbo-preserve-scroll
                                                            method="post"
                                                            action="<?= url('delete note', ['id' => $note->id]) ?>"
                                                            data-turbo-confirm="<?= _('Are you sure that you want to delete this note?') ?>"
                                                            role="menuitem"
                                                        >
                                                            <button type="submit" class="popup__item popup__item--button">
                                                                <?= icon('trash') ?>
                                                                <?= _('Delete') ?>
                                                            </button>

                                                            <input type="hidden" name="csrf_token" value="<?= csrf_token('notes\\DeleteNote') ?>" />
                                                        </form>
                                                    </nav>
                                                </details>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endforeach; ?>
                    </article>
                <?php else: ?>
                    <article class="panel text--center">
                        <?= _('No notes have yet been taken.') ?>
                    </article>
                <?php endif; ?>
            </div>

            <?php if ($form): ?>
                <form
                    data-turbo-preserve-scroll
                    method="post"
                    action="<?= url('links/create note', ['link_id' => $link->id]) ?>"
                    data-controller="autosave"
                    data-action="turbo:submit-start@document->autosave#clear"
                >
                    <?= $this->include('alerts/_error.phtml', ['message' => $form->error('@base')]) ?>

                    <div class="form-group">
                        <label for="content">
                            <?= _('What do you retain from this content?') ?>
                        </label>

                        <?php if ($form->isInvalid('content')): ?>
                            <p id="content-error" class="form-group__error">
                                <?= _('Error:') ?>
                                <?= $form->error('content') ?>
                            </p>
                        <?php endif; ?>

                        <textarea
                            id="content"
                            name="content"
                            required
                            data-controller="text-editor"
                            data-action="text-editor#refresh keyup->autosave#save"
                            aria-describedby="content-caption"
                            <?php if ($form->isInvalid('content')): ?>
                                aria-errormessage="content-error"
                                aria-invalid="true"
                            <?php endif; ?>
                        ><?= protect($form->content) ?></textarea>

                        <p id="content-caption" class="form-group__caption">
                            <?= _('You can format the content in Markdown and use #tags.') ?>
                        </p>
                    </div>

                    <?php if ($form->isMastodonEnabled()): ?>
                        <div class="form-group">
                            <input
                                type="checkbox"
                                id="share-on-mastodon"
                                name="share_on_mastodon"
                                <?= $form->share_on_mastodon ? 'checked' : '' ?>
                            />

                            <label class="label--checkbox" for="share-on-mastodon">
                                <?= _('Share on Mastodon') ?>
                            </label>
                        </div>
                    <?php endif; ?>

                    <div class="form__actions">
                        <button type="submit" class="button--primary">
                            <?= _('Add a note') ?>
                        </button>
                    </div>

                    <input type="hidden" name="csrf_token" value="<?= csrf_token($form) ?>" />
                </form>
            <?php endif; ?>
        </div>

        <?php if ($suggested_links): ?>
            <div class="panel flow">
                <p class="text--bold">
                    <?= _('See notes from:') ?>
                </p>

                <ul class="list--no-style flow flow--small">
                    <?php foreach ($suggested_links as $suggested_link): ?>
                        <?php $suggested_link_owner = $suggested_link->owner(); ?>
                        <li>
                            <img class="avatar" src="<?= url_avatar($suggested_link_owner->avatar_filename) ?>" alt="">
                            <a class="anchor--discreet" href="<?= url('link', ['id' => $suggested_link->id]) ?>">
                                <?= $suggested_link_owner->username ?>

                                <?php if ($suggested_link_owner->id === $current_user->id): ?>
                                    <?= _('(yourself)') ?>
                                <?php endif; ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
    </section>
</div>
